package com.chatdating.service.impl;

import com.chatdating.entity.LikeUser;
import com.chatdating.entity.Member;
import com.chatdating.entity.User;
import com.chatdating.entity.dto.MatchDto;
import com.chatdating.entity.dto.RecordMatchDto;
import com.chatdating.entity.vo.MatchResultVo;
import com.chatdating.entity.vo.MatchVo;
import com.chatdating.mapper.*;
import com.chatdating.service.MatchService;
import com.chatdating.service.TagService;
import com.chatdating.service.WatchService;
import com.chatdating.utils.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@EnableScheduling
public class MatchServiceImpl implements MatchService {

    @Autowired
    private RecordMatchMapper recordMatchMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MatchMapper matchMapper;

    @Autowired
    private MatchResultVoMapper matchResultVoMapper;

    @Autowired
    private LikeUserServiceImpl likeUserServiceImpl;

    @Autowired
    private TagService tagService;

    @Autowired
    private WatchService watchService;

    public MatchDto getMatchDto(Integer id){
        MatchDto matchDto = matchMapper.findMatchById(id);
        matchDto.setTags(tagService.findAll(id));
        return matchDto;
    }

    public MatchVo getTodayMatches(Integer userId) {
        MatchVo matchVo = new MatchVo();

        // 这里可能会用到，获取用户的年龄等信息，可以在之后筛选时使用
        User user = userMapper.findById(userId);

        Member member = memberMapper.getByUid(userId);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        RecordMatchDto recordMatchDto = recordMatchMapper.findOne(userId);
        // 没有记录,有会员记录且没过期
        if (recordMatchDto == null && member != null && now.isBefore(member.getEndTime())) {
            recordMatchMapper.insertOne(userId,1,0,30);
            recordMatchDto = recordMatchMapper.findOne(userId);
        // 没有记录,且不是会员
        }else if(recordMatchDto == null && member == null){
            recordMatchMapper.insertOne(userId,1,0,15);
            recordMatchDto = recordMatchMapper.findOne(userId);
        // 有记录，用户开通会员，重设匹配数量``
        }else if(recordMatchDto != null && member != null && now.isBefore(member.getEndTime())){
            recordMatchMapper.setOneNum(userId,30);
            recordMatchDto = recordMatchMapper.findOne(userId);
        // 有记录，用户不是会员
        }else if(recordMatchDto != null && (member == null || now.isAfter(member.getEndTime()))){
            recordMatchMapper.setOneNum(userId,15);
            recordMatchDto = recordMatchMapper.findOne(userId);
        }

        if(recordMatchDto == null){
            return null;
        }

        // 如果用户当天推荐的没看完，那就获取到继续展示
        if (recordMatchDto.getCurrently_user_id() != 0) {
            matchVo.setMatch(getMatchDto(recordMatchDto.getCurrently_user_id()));
            matchVo.setNum(recordMatchDto.getNum()-recordMatchDto.getStart()+1);
            return matchVo;
        }

        if (recordMatchDto.getStart()<recordMatchDto.getNum()){
            // MatchResultVo matchResultVo = matchResultVoMapper.getMatchResultVoById(userId);
            MatchResultVo matchResultVo = matchResultVoMapper.getMatchResultVoBySelfTagId(userId);
            // 没有可推荐的人，执行下面的if
            if (matchResultVo == null) {
                MatchDto matchDto = new MatchDto();
                matchVo.setMatch(matchDto);
                matchVo.setNum(recordMatchDto.getNum()-recordMatchDto.getStart());
                return matchVo;
            }

            matchVo.setMatch(getMatchDto(matchResultVo.getId()));
            matchVo.setNum(recordMatchDto.getNum()-recordMatchDto.getStart());
            recordMatchMapper.updataCurrently(userId,matchResultVo.getId());
            return matchVo;
        }

        return null;

    }

    @Override
    public MatchVo closeOneMatches(Integer userId, Integer closeUserId) {
        RecordMatchDto recordMatchDto = recordMatchMapper.findOne(userId);
        int start = recordMatchDto.getStart()+1;
        recordMatchMapper.updataStartOne(userId,start);
        // 清掉当前用户记录，保证每天推送的最后
        recordMatchMapper.updataCurrently(userId,0);
        watchService.insertWatch(userId,closeUserId);
        return getTodayMatches(userId);
    }

    @Override
    public MatchVo likeOneMatches(Integer userId, Integer likeUserId) {
        RecordMatchDto recordMatchDto = recordMatchMapper.findOne(userId);
        int start = recordMatchDto.getStart()+1;
        recordMatchMapper.updataStartOne(userId,start);
        recordMatchMapper.updataCurrently(userId,0);

        //添加喜欢的人的逻辑
        likeUserServiceImpl.addLikeUser(userId,likeUserId);
        watchService.insertWatch(userId,likeUserId);

        return getTodayMatches(userId);
    }

    /**
     * 每天中午12点执行匹配任务
     */
    @Scheduled(cron = "0 0 12 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void clearDailyMatchesCache(){
        //更新所用用户的开始点
        recordMatchMapper.updataStart(1);
        // 任务执行逻辑
        String currentTime = LocalDateTime.now().format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        );
        System.out.println("定时任务执行：" + currentTime + "，这是每分钟执行一次的任务");
    }
}
